package com.yuexunit.mobilenurse.module.NursingDocuments.ui;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.NursingDocuments.model.impl.DocumentRecordDetailModel;
import com.yuexunit.mobilenurse.module.NursingDocuments.presenter.impl.DocumentRecordDetailPresenter;
import com.yuexunit.mobilenurse.module.NursingDocuments.ui.view.IDocumentRecordDetailView;
import com.yuexunit.mobilenurse.widget.CustomDatePicker;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/10/24.
 */
public class Act_DocumentPainDetail extends KJActivity implements IDocumentRecordDetailView {

    @Bind(R.id.signinput_name)
    TextView signinputName;
    @Bind(R.id.signinput_bedno)
    TextView signinputBedno;
    @Bind(R.id.signinput_visitno)
    TextView signinputVisitno;
    @Bind(R.id.documentpain_object_edit)
    Spinner documentpainObjectEdit;
    @Bind(R.id.documentpain_tool_edit)
    Spinner documentpainToolEdit;
    @Bind(R.id.documentpain_part_edit)
    Spinner documentpainPartEdit;
    @Bind(R.id.documentpain_part_other_edit)
    EditText documentpainPartOtherEdit;
    @Bind(R.id.documentpain_nature_edit)
    Spinner documentpainNatureEdit;
    @Bind(R.id.documentpain_nature_other_edit)
    EditText documentpainNatureOtherEdit;
    @Bind(R.id.documentpain_static_edit)
    Spinner documentpainStaticEdit;
    @Bind(R.id.documentpain_activity_edit)
    Spinner documentpainActivityEdit;
    @Bind(R.id.documentpain_painfactor_edit)
    Spinner documentpainPainfactorEdit;
    @Bind(R.id.documentpain_painfactor_other_edit)
    EditText documentpainPainfactorOtherEdit;
    @Bind(R.id.documentpain_nondrug_edit)
    Spinner documentpainNondrugEdit;
    @Bind(R.id.documentpain_nondrug_other_edit)
    EditText documentpainNondrugOtherEdit;
    @Bind(R.id.documentpain_longdosage_edit)
    Spinner documentpainLongdosageEdit;
//    @Bind(R.id.documentpain_longdosage_other_edit)
//    EditText documentpainLongdosageOtherEdit;
    @Bind(R.id.documentpain_temporarydosage_edit)
    Spinner documentpainTemporarydosageEdit;
    @Bind(R.id.documentpain_temporarydosage_other_edit)
    EditText documentpainTemporarydosageOtherEdit;
    @Bind(R.id.documentpain_channel_edit)
    Spinner documentpainChannelEdit;
    @Bind(R.id.documentpain_menthod_edit)
    Spinner documentpainMenthodEdit;
    @Bind(R.id.documentpain_menthod_other_edit)
    EditText documentpainMenthodOtherEdit;
    @Bind(R.id.documentpain_starttime_day)
    TextView documentpainStarttimeDay;
//    @Bind(R.id.documentpain_starttime_hour)
//    Spinner documentpainStarttimeHour;
    @Bind(R.id.documentpain_endtime_day)
    TextView documentpainEndtimeDay;
//    @Bind(R.id.documentpain_endtime_hour)
//    Spinner documentpainEndtimeHour;
    @Bind(R.id.documentpain_injection_edt)
    EditText documentpainInjectionEdt;

    public String inpNo;//住院号
    public String recorder;//记录人员id

    private DocumentRecordDetailPresenter presenter;
    private CustomDatePicker customDatePicker1, customDatePicker2;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_documentpaindetail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter = new DocumentRecordDetailPresenter(new DocumentRecordDetailModel(), this);
        inpNo = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        recorder = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID);
        initDatePicker();
    }

    @Override
    public void initWidget() {
        super.initWidget();
        signinputName.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        signinputBedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        signinputVisitno.setText(inpNo);
    }

    @OnClick({R.id.titlebar_img_back, R.id.right_text, R.id.titlebar_img_menu,R.id.documentpain_starttime_day,R.id.documentpain_endtime_day})
    public void onClick(View view) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        switch (view.getId()) {
            case R.id.titlebar_img_back:
                finish();
                break;
            case R.id.right_text:
                buildValue();
                break;
            case R.id.titlebar_img_menu:
                buildValue();
                break;
            case R.id.documentpain_starttime_day:
                customDatePicker1.show(now);
                break;
            case R.id.documentpain_endtime_day:
                customDatePicker2.show(now);
                break;
        }
    }

    private void buildValue() {
        StringBuilder builder = new StringBuilder();
        if (!StringUtils.isEmpty(documentpainObjectEdit.getSelectedItem().toString())) {
            builder.append("503" + ":" + documentpainObjectEdit.getSelectedItem().toString());
        }

        if (!StringUtils.isEmpty(documentpainToolEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                builder.append(",504:" + documentpainToolEdit.getSelectedItem().toString());
            } else {
                builder.append("504:" + documentpainToolEdit.getSelectedItem().toString());
            }
        }

        if (!StringUtils.isEmpty(documentpainPartEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainPartEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",505:" + documentpainPartEdit.getSelectedItem().toString().substring(0,1));
                    builder.append(",526:" + documentpainPartOtherEdit.getText());
                }
                else {
                    builder.append(",505:" + documentpainPartEdit.getSelectedItem().toString().substring(0,1));
                }
            } else {
                if(documentpainPartEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("505:" + documentpainPartEdit.getSelectedItem().toString().substring(0, 1));
                    builder.append(",526:" + documentpainPartOtherEdit.getText());
                }
                else {
                    builder.append("505:" + documentpainPartEdit.getSelectedItem().toString().substring(0, 1));
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainNatureEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainNatureEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",506:" + documentpainNatureEdit.getSelectedItem().toString().substring(0,1));
                    builder.append(",528:" + documentpainNatureOtherEdit.getText());
                }
                else {
                    builder.append(",506:" + documentpainNatureEdit.getSelectedItem().toString().substring(0, 1));
                }
            } else {
                if(documentpainNatureEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("506:" + documentpainNatureEdit.getSelectedItem().toString().substring(0,1));
                    builder.append(",528:" + documentpainNatureOtherEdit.getText());
                }
                else {
                    builder.append("506:" + documentpainNatureEdit.getSelectedItem().toString().substring(0,1));
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainStaticEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                builder.append(",507:" + documentpainStaticEdit.getSelectedItem().toString());
            } else {
                builder.append("507:" + documentpainStaticEdit.getSelectedItem().toString());
            }
        }

        if (!StringUtils.isEmpty(documentpainActivityEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                builder.append(",640:" + documentpainActivityEdit.getSelectedItem().toString());
            } else {
                builder.append("640:" + documentpainActivityEdit.getSelectedItem().toString());
            }
        }

        if (!StringUtils.isEmpty(documentpainPainfactorEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainPainfactorEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",508:" + documentpainPainfactorEdit.getSelectedItem().toString().substring(0, 1));
                    builder.append(",530:" + documentpainPainfactorOtherEdit.getText());
                }
                else {
                    builder.append(",508:" + documentpainPainfactorEdit.getSelectedItem().toString().substring(0, 1));
                }
            } else {
                if(documentpainPainfactorEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("508:" + documentpainPainfactorEdit.getSelectedItem().toString().substring(0,1));
                    builder.append(",530:" + documentpainPainfactorOtherEdit.getText());
                }
                else {
                    builder.append("508:" + documentpainPainfactorEdit.getSelectedItem().toString().substring(0,1));
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainNondrugEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainNondrugEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",509:" + documentpainNondrugEdit.getSelectedItem().toString().substring(0, 1));
                    builder.append(",531:" + documentpainNondrugOtherEdit.getText());
                }
                else {
                    builder.append(",509:" + documentpainNondrugEdit.getSelectedItem().toString().substring(0, 1));
                }
            } else {
                if(documentpainNondrugEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("509:" + documentpainNondrugEdit.getSelectedItem().toString().substring(0,1));
                    builder.append(",531:" + documentpainNondrugOtherEdit.getText());
                }
                else {
                    builder.append("509:" + documentpainNondrugEdit.getSelectedItem().toString().substring(0,1));
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainLongdosageEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainLongdosageEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",510:" + documentpainLongdosageEdit.getSelectedItem().toString().substring(0, 1));
                }
                else {
                    builder.append(",510:" + documentpainLongdosageEdit.getSelectedItem().toString().substring(0, 1));
                }
            } else {
                if(documentpainLongdosageEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("510:" + documentpainLongdosageEdit.getSelectedItem().toString().substring(0, 1));
                }
                else {
                    builder.append("510:" + documentpainLongdosageEdit.getSelectedItem().toString().substring(0, 1));
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainTemporarydosageEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",511:" + documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0, 1));
                }
                else {
                    builder.append(",511:" + documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0, 1));
                }
            } else {
                if(documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("511:" + documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0,1));
                }
                else {
                    builder.append("511:" + documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0,1));
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainTemporarydosageOtherEdit.toString())) {
            if(documentpainLongdosageEdit.getSelectedItem().toString().substring(0,1).equals("Z") || documentpainTemporarydosageEdit.getSelectedItem().toString().substring(0,1).equals("Z")) {
                if (builder.length() != 0) {
                    builder.append(",532:" + documentpainTemporarydosageOtherEdit.toString());
                } else {
                    builder.append("532:" + documentpainTemporarydosageOtherEdit.toString());
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainChannelEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                builder.append(",512:" + documentpainChannelEdit.getSelectedItem().toString());
            } else {
                builder.append("512:" + documentpainChannelEdit.getSelectedItem().toString());
            }
        }

        if (!StringUtils.isEmpty(documentpainMenthodEdit.getSelectedItem().toString())) {
            if (builder.length() != 0) {
                if(documentpainMenthodEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append(",513:" + documentpainMenthodEdit.getSelectedItem().toString().substring(0, 1));
                    builder.append(",527:" + documentpainMenthodOtherEdit.getText());
                }
                else {
                    builder.append(",513:" + documentpainMenthodEdit.getSelectedItem().toString().substring(0, 1));
                }
            } else {
                if(documentpainMenthodEdit.getSelectedItem().toString().substring(0,1).equals("Z"))
                {
                    builder.append("513:" + documentpainMenthodEdit.getSelectedItem().toString());
                    builder.append(",527:" + documentpainMenthodOtherEdit.getText());
                }
                else {
                    builder.append("513:" + documentpainMenthodEdit.getSelectedItem().toString());
                }
            }
        }

        if (!StringUtils.isEmpty(documentpainStarttimeDay.getText())) {
            if (builder.length() != 0) {
                builder.append(",514:" + documentpainStarttimeDay.getText() );
            } else {
                builder.append("514:" + documentpainStarttimeDay.getText());
            }
        }

        if (!StringUtils.isEmpty(documentpainEndtimeDay.getText())) {
            if (builder.length() != 0) {
                builder.append(",515:" + documentpainEndtimeDay.getText() );
            } else {
                builder.append("515:" + documentpainEndtimeDay.getText());
            }
        }

        if (!StringUtils.isEmpty(documentpainInjectionEdt.getText())) {
            if (builder.length() != 0) {
                builder.append(",516:" + documentpainInjectionEdt.getText()+"ml" );
            } else {
                builder.append("516:" + documentpainInjectionEdt.getText()+"ml");
            }
        }

        Map<String, String> params = new HashMap<>();
        params.put("inpNo", inpNo);
        params.put("timestamp", System.currentTimeMillis() + "");
        params.put("timepoint", System.currentTimeMillis() + "");
        params.put("templateId", "13");
        params.put("signData", builder.toString());
        params.put("recorder", recorder);


        presenter.uploadRecord(params);

    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());

        customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                documentpainStarttimeDay.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 不显示时和分
        customDatePicker1.setIsLoop(false); // 不允许循环滚动

        customDatePicker2 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                documentpainEndtimeDay.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker2.showSpecificTime(true); // 显示时和分
        customDatePicker2.setIsLoop(true); // 允许循环滚动
    }



    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public void uploadRecord() {
        finish();
    }
}
